package org.summerframework.component.security.oauth;

import org.summerframework.component.security.oauth.exception.OAuthException;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class OAuthUserInfo implements OAuthUserInfoInterceptor {

    private List<OAuthInterceptor> oAuthInterceptors;

    public OAuthUserInfo(List<OAuthInterceptor> oAuthInterceptors) {
        this.oAuthInterceptors = oAuthInterceptors;
    }

    @Override
    public <T extends Info> T getOAuthUserInfo(String code, String redirect_uri,
                                               LoginType type) {
        //判断code是否传值
        if (StringUtils.isBlank(code)) {
            return null;
        }

        for (OAuthInterceptor authInterceptor : oAuthInterceptors) {
            if (authInterceptor.supportsType(type)) {
                if (authInterceptor.getOAuthInfo() == null) {
                    throw new OAuthException(OAuthResultCode.OAUTH_NOT_SETTING);
                }

                AccessToken accessToken = authInterceptor.getAccessToken(code);
                accessToken.setRedirectURL(redirect_uri);

                //获取accessToken
                Info resultInfo = authInterceptor.getResultInfo(accessToken);
                return (T) authInterceptor.getInfo(resultInfo);
            }
        }

        throw new OAuthException(OAuthResultCode.OAUTH_NOT_SETTING);
    }
}
